package com.example.statistics.weight

import android.content.Context
import android.graphics.PorterDuff
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import com.example.statistics.R
import com.example.statistics.ex.glide
import kotlinx.android.synthetic.main.layout_top_bar.view.*
import org.jetbrains.anko.sdk27.coroutines.onClick

class TopBarLayout @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
    private var view: View

    init {
        view = LayoutInflater.from(context).inflate(R.layout.layout_top_bar, this, false)
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.TopBarLayout)

        val isShowRightImage =
            typedArray.getBoolean(R.styleable.TopBarLayout_isShowRightImage, false)
        val isShowRightText =
            typedArray.getBoolean(R.styleable.TopBarLayout_isShowRightText, false)
        val title = typedArray.getString(R.styleable.TopBarLayout_title)
            ?: context.getString(R.string.app_name)
        view.iv_top_bar_right.visibility = if (isShowRightImage) View.VISIBLE else View.GONE
        view.tv_top_bar_right.visibility = if (isShowRightText) View.VISIBLE else View.GONE
        view.tv_top_bar_title.text = title
        typedArray.recycle()
        addView(view)
    }

    fun title(title: String) {
        view.tv_top_bar_title.text = title
    }

    fun topBarRightText(text: String, body: () -> Unit) {
        view.tv_top_bar_right.visibility = View.VISIBLE
        view.tv_top_bar_right.text = text
        view.tv_top_bar_right.onClick {
            body()
        }
    }

    fun topBarRightImage(
        image: Int = R.drawable.ic_blank_add,
        color: Int? = null,
        body: () -> Unit
    ) {
        if (color != null) view.iv_top_bar_right.setColorFilter(color, PorterDuff.Mode.SRC_IN)
        view.iv_top_bar_right.visibility = View.VISIBLE
        view.iv_top_bar_right.glide(image)
        view.iv_top_bar_right.onClick {
            body()
        }
    }

}